package com.aboo.frame;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;
import org.springframework.transaction.interceptor.TransactionInterceptor;

import javax.annotation.Resource;

@Configuration
@Aspect
public class DbTradeTransactionAdviceConfig {

    private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.aboo..service.*.*(..))";

    @Resource(name = "tradeTransactionManager")
    private PlatformTransactionManager tradeTransactionManager;

    /**
     * 方法名：  tradeTxAdvice
     * 描述：  事物规则配置
     *
     * @return
     * @author 娄安
     * 创建时间：2019年9月27日 下午1:25:57
     */
    @Bean(name = "tradeTxAdvice")
    public TransactionInterceptor tradeTxAdvice() {
        DefaultTransactionAttribute txAttrRequired = new DefaultTransactionAttribute();
        txAttrRequired.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        DefaultTransactionAttribute txAttrSupport = new DefaultTransactionAttribute();
        txAttrSupport.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);

        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.addTransactionalMethod("save*", txAttrRequired);
        source.addTransactionalMethod("get*", txAttrSupport);
        return new TransactionInterceptor(tradeTransactionManager, source);
    }

    /**
     * 方法名：  tradeTxAdviceAdvisor
     * 描述：  事物切面
     *
     * @return
     * @author 娄安
     * 创建时间：2019年9月27日 下午1:26:16
     */
    @Bean(name = "tradeTxAdviceAdvisor")
    public Advisor tradeTxAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, tradeTxAdvice());
    }

}
